// app.js
App({
  onLaunch() {
    console.log('安心住助手小程序启动')
    
    // 初始化应用
    this.initApp()
  },

  // 初始化应用
  initApp() {
    try {
      // 清理过期数据
      this.cleanupExpiredData()
      
      // 检查应用版本
      this.checkAppVersion()
      
      console.log('应用初始化完成')
    } catch (error) {
      console.error('应用初始化失败:', error)
    }
  },

  // 清理过期数据
  cleanupExpiredData() {
    try {
      // 清理可能存在的旧版本日志数据
      wx.removeStorageSync('logs')
      
      // 清理超过30天的检测历史
      const history = wx.getStorageSync('detection_history') || []
      const thirtyDaysAgo = Date.now() - (30 * 24 * 60 * 60 * 1000)
      const filteredHistory = history.filter(record => 
        record.timestamp && record.timestamp > thirtyDaysAgo
      )
      
      if (filteredHistory.length !== history.length) {
        wx.setStorageSync('detection_history', filteredHistory)
        console.log(`清理了 ${history.length - filteredHistory.length} 条过期历史记录`)
      }
    } catch (error) {
      console.error('清理数据失败:', error)
    }
  },

  // 检查应用版本
  checkAppVersion() {
    try {
      const currentVersion = this.globalData.appInfo.version
      const savedVersion = wx.getStorageSync('app_version')
      
      if (savedVersion !== currentVersion) {
        console.log(`应用版本更新: ${savedVersion} -> ${currentVersion}`)
        wx.setStorageSync('app_version', currentVersion)
        
        // 版本更新时的处理逻辑
        this.handleVersionUpdate(savedVersion, currentVersion)
      }
    } catch (error) {
      console.error('版本检查失败:', error)
    }
  },

  // 处理版本更新
  handleVersionUpdate(oldVersion, newVersion) {
    try {
      // 这里可以添加版本更新时需要执行的逻辑
      // 比如清理不兼容的数据、显示更新说明等
      console.log('处理版本更新逻辑')
    } catch (error) {
      console.error('版本更新处理失败:', error)
    }
  },

  // 全局分享配置
  onShareAppMessage() {
    return {
      title: '安心住助手 - 守护您的隐私安全',
      desc: '专业的隐私检测工具，镜头、WiFi、磁场、蓝牙四重检测',
      path: '/pages/index/index'
    }
  },

  // 全局朋友圈分享配置
  onShareTimeline() {
    return {
      title: '安心住助手 - 守护您的隐私安全'
    }
  },
  
  globalData: {
    userInfo: null,
    // 应用信息
    appInfo: {
      version: '0.0.1',
      name: '安心住助手',
      year: '2025'
    },
    // 全局配置
    config: {
      // 磁场检测阈值
      magneticThreshold: 50,
      // WiFi扫描间隔
      wifiScanInterval: 3000,
      // 相机检测设置
      cameraSettings: {
        flashEnabled: true,
        screenLightEnabled: true
      }
    }
  },

  // 全局工具方法
  utils: {
    // 格式化时间
    formatTime(date) {
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()

      return `${[year, month, day].map(this.formatNumber).join('/')} ${[hour, minute, second].map(this.formatNumber).join(':')}`
    },

    formatNumber(n) {
      n = n.toString()
      return n[1] ? n : `0${n}`
    },

    // 生成唯一ID
    generateId() {
      return Date.now().toString(36) + Math.random().toString(36).substr(2)
    },

    // 风险等级评估
    assessRiskLevel(result) {
      let riskScore = 0
      
      // 相机检测结果评分
      if (result.camera && result.camera.suspiciousPoints) {
        riskScore += result.camera.suspiciousPoints.length * 30
      }
      
      // WiFi检测结果评分
      if (result.wifi && result.wifi.suspiciousDevices) {
        riskScore += result.wifi.suspiciousDevices.length * 40
      }
      
      // 磁场检测结果评分
      if (result.magnetic && result.magnetic.anomalies) {
        riskScore += result.magnetic.anomalies.length * 20
      }
      
      // 蓝牙检测结果评分
      if (result.bluetooth && result.bluetooth.suspiciousDevices) {
        riskScore += result.bluetooth.suspiciousDevices.length * 35
      }
      
      if (riskScore >= 80) return 'high'
      if (riskScore >= 40) return 'medium'
      return 'low'
    },

    // 获取用户设置
    getUserSettings() {
      try {
        const defaultSettings = {
          // 检测设置
          magneticThreshold: 50,
          magneticSensitivity: 5,
          magneticSampleInterval: 500,
          bluetoothScanDuration: 30,
          wifiScanDuration: 30,
          cameraFlashEnabled: true,
          screenLightEnabled: false,
          
          // 通知设置
          vibrationEnabled: true,
          soundEnabled: false,
          
          // 隐私设置
          savePhotos: false,
          autoSaveResults: true,
          
          // 其他设置
          theme: 'auto',
          language: 'zh-CN'
        }
        
        const savedSettings = wx.getStorageSync('user_settings') || {}
        return { ...defaultSettings, ...savedSettings }
      } catch (error) {
        console.error('获取用户设置失败:', error)
        return {
          magneticThreshold: 50,
          magneticSensitivity: 5,
          magneticSampleInterval: 500,
          bluetoothScanDuration: 30,
          vibrationEnabled: true,
          soundEnabled: false
        }
      }
    },

    // 保存用户设置
    saveUserSettings(settings) {
      try {
        const currentSettings = this.getUserSettings()
        const newSettings = { ...currentSettings, ...settings }
        wx.setStorageSync('user_settings', newSettings)
        return true
      } catch (error) {
        console.error('保存用户设置失败:', error)
        return false
      }
    }
  }
})
